import pandas as pd
import numpy as np
from matplotlib import pyplot
from numpy import interp

from sklearn.metrics import roc_curve, auc
from sklearn.metrics import precision_recall_curve, average_precision_score
from sklearn.model_selection import KFold
from DNN_auto import DNN_auto
from fold5 import DNN, preprocess_labels, transfer_array_format, calculate_performace
from prepare_data import prepare_data

# data = pd.read_csv("..\data\cs3.csv", header=None, delimiter=" ")
# data2 = pd.read_csv("..\data\ds3.csv", header=None, delimiter=" ")
# 3
# data = np.loadtxt("..\data\circRNA2Disease\multiview\CircRNA2Disease_circGIPsimilarity.txt")
# data2 = np.loadtxt("..\data\circRNA2Disease\multiview\CircRNA2Disease_disGIPsimilarity.txt")
# data = pd.read_csv("..\KernelFusion-code\Kcom1_circrna2disease.csv", header=None)
# data2 = pd.read_csv("..\KernelFusion-code\Kcom2_circrna2disease.csv", header=None)
# interaction = pd.read_csv("..\data\circRNA2Disease\CircRNA2Disease_Association.csv", header=None)
# 1
data = pd.read_csv("..\data\Kcom1_data1.csv", header=None)
data2 = pd.read_csv("..\data\Kcom2_data1.csv", header=None)
interaction = pd.read_csv("..\data\circR2Disease\circRNA_disease.csv", header=None)
# 2
# data = pd.read_csv("KCOM1.csv", header=None)
# data2 = pd.read_csv("KCOM2.csv", header=None)
# interaction = pd.read_csv("Circ2Disease_Association.csv", header=None, delimiter=",")

K_COM1 = np.array(data)
K_COM2 = np.array(data2)
interaction = np.array(interaction, dtype=int)
y_train = interaction

# X_data = np.concatenate((K_COM1, K_COM2), axis=1)
X_data, label, test, test_index = prepare_data(K_COM1, K_COM2, y_train)
# np.savetxt('test_index1.csv', test_index, delimiter=",")

X_data1, X_data2 = transfer_array_format(X_data)
X_data = np.concatenate((X_data1, X_data2), axis=1)  # 对应行的数组进行拼接,样本数650，特征维数673

test_data1, test_data2 = transfer_array_format(test)
test_data = np.concatenate((test_data1, test_data2), axis=1)

encoder, X_data = DNN_auto(X_data)  # 降维到128
y = preprocess_labels(label)  # 前270有关联，后270无关联

num_cross_val = 5
all_performance_DNN = []
mean_tpr = 0.0
mean_fpr = np.linspace(0, 1, 100)
t = 0

mean_recall = np.linspace(0,1,100)
mean_precision = []
kf = KFold(n_splits=num_cross_val, shuffle=True)
for train_index, test_index in kf.split(X_data, y):
    train1 = X_data[train_index]
    train_label = y[train_index]
    test1 = X_data[test_index]
    test_label = y[test_index]
# for fold in range(num_cross_val):
#     train1 = np.array([x for i, x in enumerate(X_data) if i % num_cross_val != fold])
#     test1 = np.array([x for i, x in enumerate(X_data) if i % num_cross_val == fold])
#     train_label = np.array([x for i, x in enumerate(y) if i % num_cross_val != fold])
#     test_label = np.array([x for i, x in enumerate(y) if i % num_cross_val == fold])

    # 标签真值
    real_labels = []
    for val in test_label:
        if val[0] == 1:
            real_labels.append(0)
        else:
            real_labels.append(1)
    # 训练标签值
    train_label_new = []
    for val in train_label:
        if val[0] == 1:
            train_label_new.append(0)
        else:
            train_label_new.append(1)
    class_index = 0
    class_index = class_index + 1

    prefilter_train = train1
    prefilter_test = test1

    # clf = svm.SVC(kernel='poly',degree=3,gamma=2,probability=True)
    # clf = RandomForestClassifier(n_estimators=100)

    model_DNN = DNN()

    train_label_new_forDNN = np.array([[0, 1] if i == 1 else [1, 0] for i in train_label_new])
    print(train_label_new_forDNN[0])
    # training
    model_DNN.fit(prefilter_train, train_label_new_forDNN, batch_size=150, nb_epoch=40, shuffle=True)

    # 使用predict()方法进行预测时，返回值是数值，表示样本属于每一个类别的概率；使用predict_classes()方法进行预测时，返回的是类别的索引，即该样本所属的类别标签。
    proba = model_DNN.predict_classes(prefilter_test, batch_size=150, verbose=True)  # predicting classes
    proba2 = model_DNN.predict(prefilter_test, batch_size=150, verbose=True)  # predicting probabilities
    # np.savetxt('../data/output/predict_score{}.csv'.format(fold), proba2, delimiter=",")
    # predict_proba返回的是一个n行k列的数组， 第i行第j列上的数值是模型预测 第i个预测样本为某个标签的概率，并且每一行的概率和为1。
    ae_y_pred_prob = model_DNN.predict_proba(prefilter_test, batch_size=150, verbose=True)
    # np.savetxt('test_index1.csv', ae_y_pred_prob[:, 1], delimiter=",")
    # 计算结果表现
    acc, precision, sensitivity, specificity, MCC, f1_score = calculate_performace(len(real_labels), proba, real_labels)
    fpr, tpr, auc_thresholds = roc_curve(real_labels, ae_y_pred_prob[:, 1])
    auc_score = auc(fpr, tpr)

    precision1, recall, pr_threshods = precision_recall_curve(real_labels, ae_y_pred_prob[:, 1])
    # average_precision = average_precision_score(real_labels, ae_y_pred_prob[:, 1])
    # mean_average_precision.append(average_precision)
    mean_precision.append(precision1)
    # mean_precision += interp(mean_recall, recall, precision1)
    aupr_score = auc(recall, precision1)

    print("AUTO-DNN:", acc, precision, sensitivity, specificity, MCC, auc_score, aupr_score, f1_score)
    all_performance_DNN.append([acc, precision, sensitivity, specificity, MCC, auc_score, aupr_score, f1_score])
    t = t + 1

    # ROC绘图
    pyplot.plot(fpr, tpr, label='ROC fold %d (AUC = %0.4f)' % (t, auc_score))
    mean_tpr += interp(mean_fpr, fpr, tpr)
    mean_tpr[0] = 0.0



    pyplot.xlabel('False positive rate, (1-Specificity)')
    pyplot.ylabel('True positive rate,(Sensitivity)')
    pyplot.title('Receiver Operating Characteristic curve: 10-Fold CV')
    pyplot.legend()
    # PR绘图
    # pyplot.plot(recall, precision1, label='ROC fold %d (AUC = %0.4f)' % (t, aupr_score))
    # pyplot.xlabel('recall')
    # pyplot.ylabel('precision')
    # pyplot.title('Precision-Recall curve: 5-Fold CV')
    # pyplot.legend()

Mean_Result = np.mean(np.array(all_performance_DNN), axis=0)
print('mean performance of my model ')
print(np.mean(np.array(all_performance_DNN), axis=0))

print('---' * 20)
print('Mean-Accuracy=', Mean_Result[0], '\n Mean-precision=', Mean_Result[1])
print('Mean-Sensitivity=', Mean_Result[2], '\n Mean-Specificity=', Mean_Result[3])
print('Mean-MCC=', Mean_Result[4], '\n' 'Mean-auc_score=', Mean_Result[5])
print('Mean-Aupr-score=', Mean_Result[6], '\n' 'Mean_F1=', Mean_Result[7])
print('---' * 20)
mean_tpr /= num_cross_val
mean_tpr[-1] = 1.0

mean_auc = auc(mean_fpr, mean_tpr)
# mean_precision /= num_cross_val
# mean_precision[-1] = 1.0
aver_precision = sum(mean_precision) / len(mean_precision)
pyplot.plot(mean_recall, aver_precision)
# pyplot.show()
np.savetxt('fpr1.csv', mean_fpr, delimiter=",")
np.savetxt('tpr1.csv', mean_tpr, delimiter=",")
np.savetxt('precision1.txt', mean_precision, delimiter=",")
np.savetxt('recall1.txt', mean_recall, delimiter=",")

pyplot.plot(mean_fpr, mean_tpr, '--', linewidth=2.0, label='Mean ROC (AUC = %0.4f)' % mean_auc)
pyplot.legend()
pyplot.show()

# Mean_Result = []
# pyplot.plot(mean_fpr, mean_tpr, '--', linewidth=2.5, label='Mean ROC (AUC = %0.4f)' % mean_auc)
# pyplot.legend()
# pyplot.show()



# encoder, test_data = DNN_auto(test_data)
# proba2 = model_DNN.predict(test_data,batch_size=200,verbose=True)
# ae_y_pred_prob = model_DNN.predict_proba(X_data, batch_size=200, verbose=True)
# np.savetxt('predict_score.csv', ae_y_pred_prob, delimiter=",")
